package cn.k.controller;

import cn.k.domain.Employee;
import cn.k.qo.JSONResult;
import cn.k.service.IEmployeeService;
import cn.k.service.IPermissionService;
import cn.k.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    //{"success" :true "msg":"登录成功"}
    @RequestMapping("/userLogin")
    @ResponseBody
    public JSONResult login(String username, String password){

        try {
            Employee employee=employeeService.login(username,password);
            if (employee!=null){
                //存入session
                UserContext.setEmployee(employee);
            }
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            SecurityUtils.getSubject().login(token);
            return new JSONResult(true,"登录成功");
        } catch (UnknownAccountException e) {
            return new JSONResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JSONResult(false, "密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, "登录异常，请联系管理员");
        }

        /*if (employee!=null){
            //往session存入登录员工对象
            UserContext.setEmployee(employee);

            if (!employee.isAdmin()){ //不是管理员,为了性能
                List<String> expression = permissionService.queryExpressionByEmployeeId(employee.getId());
                UserContext.setExpression(expression);
            }

            return  new JSONResult(true,"登录成功");
        }else {
            return  new JSONResult(false,"登录失败");
        }*/
    }

    @RequestMapping("/userLogout")
    public String  logout(HttpSession session){
        //登出杀死进程
        session.invalidate();
        //跳转到登录页面
        return "redirect:/static/login.html";
    }

    //访问没有权限页面
    @RequestMapping("/nopermission")
    public String  nopermission(){
        return "common/nopermission";
    }

}
